angular.module('Caltech')
.controller('customerItemController', function ($scope, Restangular, $state, $stateParams, Constants) {
    'use strict';

    var defautlModel = {
        salesmanId: Constants.accountInfo.id,
        salesmanName: Constants.accountInfo.fullName,
        isExistUsername: false,
        createdBy: Constants.accountInfo.id,
        updatedBy: Constants.accountInfo.id
    };

    if ($stateParams.id) {
        Restangular.one('customer', $stateParams.id).get().then(function (data) {
            $scope.model = data;
        });
    } else {
        $scope.model = defautlModel;
    }

    $scope.update = function (model) {
        model.updatedBy = Constants.accountInfo.id;
        model.salesmanId = Constants.accountInfo.id;
        model.salesmanName = Constants.accountInfo.fullName;
        return model.put().then(function () {
            $state.forceReload();
        });
    };

    $scope.save = function (model) {
        model.createdBy = Constants.accountInfo.id;
        model.updatedBy = Constants.accountInfo.id;
        return Restangular.all('customer').post(model).then(function (id) {
            $state.go('customer-item', { id: id });
        });
    };

    $scope.remove = function (model) {
        return model.remove().then(function () {
            history.back();
        });
    }
});